package com.sgidi.einvoice.web;

import com.sgidi.einvoice.models.Invoice;
import com.sgidi.einvoice.models.InvoiceResult;
import com.sgidi.einvoice.service.PdfQrExtractor;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/invoice")
public class InvoiceController {

    @Value("${user.dir}/data/invoice")
    private String backupPath;

    @PostMapping(value = "/extract")
    public InvoiceResult extract(@RequestParam("file") MultipartFile file) {
        return processEachFile(file);
    }

    @RequestMapping(value = "/extract/bundle")
    public List<InvoiceResult> extractBundle(@RequestParam("files") List<MultipartFile> files) {
        List<InvoiceResult> invoiceResults = new java.util.ArrayList<>();
        files.forEach(file -> {
            InvoiceResult invoice = processEachFile(file);
            if (null != invoice) {
                invoiceResults.add(invoice);
            }
        });
        return invoiceResults;
    }

    private synchronized InvoiceResult processEachFile(MultipartFile file) {
        InvoiceResult result = new InvoiceResult();
        String originalFilename = file.getOriginalFilename();
        result.setFileName(originalFilename);
        boolean isPdfFile = originalFilename.toLowerCase().endsWith(".pdf");
        if (!isPdfFile) return null;
        String fileName = UUID.randomUUID() + ".pdf";
        File dest = new File(backupPath, fileName);
        dest.getParentFile().mkdirs();
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), dest);
            Invoice pdf = PdfQrExtractor.extract(dest);
            if (pdf == null) {
                throw new Exception("无法解析发票，程序识别不出二维码");
            }
            result.setInvoice(pdf);
        } catch (Exception e) {
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        } finally {
            if (dest.exists()) {
                dest.delete();
            }
        }
        return result;
    }
}
